<template>
  <div class="h-full flex items-center" ref="triggerRef">
    <!-- 触发按钮 -->
    <div @click.stop="toggleDropdown" class="relative">
      <slot name="trigger">
        <BaseIcon name="uni-more" className="!text-text-white-2 size-[1.125rem]"/>
      </slot>
      <!-- 弹出菜单 -->
      <transition name="fade">
        <div
          v-if="visible"
          class="absolute mt-4 bg-bg-black-1 text-white rounded-xl z-50 shadow-md max-h-[10rem] overflow-y-scroll"
          @click.stop="visible = false; emits('toggle', false)"
          :class="[props.position === 'left' ? 'left-0' : props.position === 'right' ? 'right-0' : 'transform -translate-x-1/2 left-1/2']"
        >
          <slot name="menu" />
        </div>
      </transition>
    </div>

    
  </div>
</template>

<script lang="ts" setup>

const visible = ref(false)
const triggerRef = ref<HTMLElement>()

const emits = defineEmits(['update:modelValue', 'change', 'toggle'])

watch(visible, (val) => {
  emits('update:modelValue', val)
})

interface Props {
  position?: 'left' | 'center' | 'right'
  modelValue?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  position: 'left',
  modelValue: false
})
defineOptions({
  name: 'BaseDropdown',
})
const toggleDropdown = () => {
  visible.value = !visible.value
  emits('toggle', visible.value)
}

const handleClickOutside = (event: MouseEvent) => {
  if (triggerRef.value && !triggerRef.value.contains(event.target as Node)) {
    visible.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
